import React, { useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import { Button, Col, DatePicker, Empty, Form, Icon, Input, Row, Select, Typography, message } from 'antd';
import { useRequest, useDictionary } from '@/hooks';
import useDynamicList from '@/hooks/useDynamicList';
import moment from 'moment';
import { formatDateRange } from '@/utils/utils';
import FormContainer from './FormContainer';
import styles from './index.less';

const { Text } = Typography;

const RANGE_PICKER_FORMAT_YYYY_MM_DD = 'YYYY-MM-DD';

/**
 * 员工档案 - 教育经历
 */
const EducationalExperienceSection = ({ formData, onChange, readonly, saveAction }) => {
    const formRef = useRef();
    // 提交
    const { run: submitRun } = useRequest(submitData => saveAction && saveAction(submitData), {
        manual: true
    });
    // 字典数据
    const [academicYearList, getAcademicYearText] = useDictionary('academicYear');
    const [degreeTypeList, getDegreeTypeText] = useDictionary('agreeType');
    const [educationTypeList, getEducationTypeText] = useDictionary('degreeType');
    // 列表管理
    const {
        list: eduList,
        remove: eduListRemove,
        push: eduListPush,
        getKey: eduListGetKey,
        resetList: eduListReset
    } = useDynamicList([]);

    useEffect(() => {
        // 重置列表的值
        eduListReset(formData.eduList);
    }, [eduListReset, formData.eduList]);

    useEffect(() => {
        // 表单赋值
        formRef.current.getFieldDecorator('eduList', { initialValue: formData.eduList || [] });
    }, [formData.eduList]);

    // 保存
    const handleSubmit = async values => {
        const submitData = Object.assign({
            employeeCode: formData.employeeCode,
            highestDegree: values.highestDegree,
            newList: eduList.map((item, index) => {
                const key = eduListGetKey(index);
                return {
                    startTime: values.startTime[key][0]?.format(RANGE_PICKER_FORMAT_YYYY_MM_DD),
                    endTime: values.startTime[key][1]?.format(RANGE_PICKER_FORMAT_YYYY_MM_DD),
                    graduateSchool: values.graduateSchool[key],
                    major: values.major[key],
                    degree: values.degree[key],
                    certificate: values.certificate[key],
                    academicYear: values.academicYear[key]
                };
            })
        });
        // 提交
        const res = await submitRun(submitData);
        if (res.code === 10000) {
            message.success(res.msg);
            onChange({
                highestDegree: submitData.highestDegree,
                eduList: submitData.newList
            });
        } else {
            message.error(res.msg);
        }
    };

    // 取消编辑
    const handleCancel = () => {
        eduListReset(formData.eduList);
    };

    // 取消编辑
    const handleEdit = () => {
        if (eduList.length === 0) {
            eduListPush({});
        }
    };

    // 处理日期为空的情况
    const preprocessDateRange = (startDate, endDate) => [startDate && moment(startDate), endDate && moment(endDate)];

    // 很奇怪, 日期选择组件不能自动赋值
    const handleSetStartTimeValue = (values, keys) => {
        formRef.current.setFieldsValue({ [keys]: values });
    };

    // render
    return (
        <FormContainer
            ref={formRef}
            title="教育经历"
            hasEditAuth={!readonly && !!saveAction}
            onSubmit={handleSubmit}
            onCancel={handleCancel}
            onEdit={handleEdit}
        >
            {({ getFieldDecorator }, editStatus) => (
                <div className={styles.dynamicList}>
                    <Row gutter={24} style={{ marginBottom: '10px' }}>
                        <Col span={12}>
                            <Form.Item label="最高学历">
                                {eduList.filter(item => item.degree && item.degree !== '8').length
                                    ? getDegreeTypeText(
                                          Math.max(
                                              ...eduList
                                                  .filter(item => item.degree && item.degree !== '8')
                                                  .map(item => Number(item.degree))
                                          ).toString()
                                      )
                                    : '--'}
                            </Form.Item>
                        </Col>
                    </Row>
                    {eduList.length === 0 && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                    <div className={styles.dynamicListContainer}>
                        {eduList.map((item, index) => (
                            <div key={eduListGetKey(index)} className={styles.dynamicListItem}>
                                {editStatus && (
                                    <Icon
                                        onClick={() => eduListRemove(index)}
                                        className={styles.dynamicListClose}
                                        type="close-circle"
                                        theme="filled"
                                    />
                                )}
                                <Row gutter={24}>
                                    <Col span={12}>
                                        <Form.Item label="起止时间">
                                            {editStatus
                                                ? getFieldDecorator(`startTime[${eduListGetKey(index)}]`, {
                                                      initialValue: preprocessDateRange(item?.startTime, item?.endTime),
                                                      rules: [{ required: true, message: '起止时间不能为空' }]
                                                  })(
                                                      <DatePicker.RangePicker
                                                          format={RANGE_PICKER_FORMAT_YYYY_MM_DD}
                                                          style={{ width: '100%' }}
                                                          onPanelChange={values =>
                                                              handleSetStartTimeValue(
                                                                  values,
                                                                  `startTime[${eduListGetKey(index)}]`
                                                              )
                                                          }
                                                      />
                                                  )
                                                : formatDateRange(item?.startTime, item?.endTime, 'YYYY-MM-DD')}
                                        </Form.Item>
                                        <Form.Item label="专业">
                                            {editStatus ? (
                                                getFieldDecorator(`major[${eduListGetKey(index)}]`, {
                                                    initialValue: item?.major ?? undefined,
                                                    rules: [
                                                        {
                                                            required: true,
                                                            message: '请输入专业名称'
                                                        },
                                                        {
                                                            min: 1,
                                                            max: 50,
                                                            message: '请输入1~50个字符'
                                                        },
                                                        {
                                                            pattern: /^[^\s]+(\s+[^\s]+)*$/,
                                                            message: '此处不能输入空格'
                                                        }
                                                    ]
                                                })(<Input placeholder="请输入专业名称" />)
                                            ) : (
                                                <div className="multiLineText">{item?.major}</div>
                                            )}
                                        </Form.Item>
                                        <Form.Item label="学制">
                                            {editStatus ? (
                                                getFieldDecorator(`academicYear[${eduListGetKey(index)}]`, {
                                                    initialValue: item?.academicYear || undefined
                                                })(
                                                    <Select placeholder="请选择学制">
                                                        {academicYearList?.map(option => (
                                                            <Select.Option value={option.value} key={option.value}>
                                                                {option.text}
                                                            </Select.Option>
                                                        ))}
                                                    </Select>
                                                )
                                            ) : (
                                                <Text>{getAcademicYearText(item?.academicYear || '--')}</Text>
                                            )}
                                        </Form.Item>
                                    </Col>
                                    <Col span={12}>
                                        <Form.Item label="学校名称">
                                            {editStatus ? (
                                                getFieldDecorator(`graduateSchool[${eduListGetKey(index)}]`, {
                                                    initialValue: item?.graduateSchool ?? undefined,
                                                    rules: [
                                                        {
                                                            required: true,
                                                            message: '请输入学校名称'
                                                        },
                                                        {
                                                            min: 1,
                                                            max: 50,
                                                            message: '请输入1~50个字符'
                                                        },
                                                        {
                                                            pattern: /^[^\s]+(\s+[^\s]+)*$/,
                                                            message: '此处不能输入空格'
                                                        }
                                                    ]
                                                })(<Input placeholder="请输入学校名称" />)
                                            ) : (
                                                <div className="multiLineText">{item?.graduateSchool}</div>
                                            )}
                                        </Form.Item>
                                        <Form.Item label="学历">
                                            {editStatus ? (
                                                getFieldDecorator(`degree[${eduListGetKey(index)}]`, {
                                                    initialValue: item?.degree || undefined,
                                                    rules: [
                                                        {
                                                            required: true,
                                                            message: '请选择学历类型'
                                                        }
                                                    ]
                                                })(
                                                    <Select placeholder="请选择学历类型">
                                                        {degreeTypeList?.filter(v => v.remark !== '1')?.map(option => (
                                                            <Select.Option value={option.value} key={option?.value}>
                                                                {option?.text}
                                                            </Select.Option>
                                                        ))}
                                                    </Select>
                                                )
                                            ) : (
                                                <Text>{getDegreeTypeText(item?.degree || '--')}</Text>
                                            )}
                                        </Form.Item>
                                        <Form.Item label="学位">
                                            {editStatus ? (
                                                getFieldDecorator(`certificate[${eduListGetKey(index)}]`, {
                                                    initialValue: item?.certificate || undefined
                                                })(
                                                    <Select placeholder="请选择学位类型">
                                                        {educationTypeList?.map(option => (
                                                            <Select.Option value={option.value} key={option?.value}>
                                                                {option?.text}
                                                            </Select.Option>
                                                        ))}
                                                    </Select>
                                                )
                                            ) : (
                                                <Text>{getEducationTypeText(item?.certificate || '--')}</Text>
                                            )}
                                        </Form.Item>
                                    </Col>
                                </Row>
                            </div>
                        ))}
                    </div>
                    {editStatus && eduList.length < 10 ? (
                        <Button style={{ marginTop: '20px' }} block onClick={() => eduListPush({})}>
                            +添加教育经历
                        </Button>
                    ) : null}
                </div>
            )}
        </FormContainer>
    );
};

// prop
EducationalExperienceSection.propTypes = {
    formData: PropTypes.object.isRequired,
    onChange: PropTypes.func.isRequired,
    saveAction: PropTypes.func,
    readonly: PropTypes.bool
};

EducationalExperienceSection.defaultProps = {
    saveAction: null,
    readonly: false
};

export default EducationalExperienceSection;
